package com.luch.controller;

import com.luch.domain.Result;
import com.luch.domain.User;
import com.luch.eaums.ResultEnum;
import com.luch.respository.UserRespository;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;


/**
 * Creator lh on 2017/8/15 10:00.
 * Email:luchefg@gmail.com
 * Description:
 */
@CrossOrigin(origins = "*")
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserRespository userRespository;

    @ApiOperation(value = "添加用户", notes = "根据user对象创建")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "body")
    @PostMapping("/user")
    public Result<User> userAdd(@Valid User user, BindingResult bindingResult) {
        log.debug("params---" + user.toString());
        if (bindingResult.hasErrors()) {
            return new Result<>(ResultEnum.FAILED.getCode(), bindingResult.getFieldError().getDefaultMessage());
        } else {
            if (user.getName() == null) {
                return new Result<>(ResultEnum.PARAMS_ERROR);
            } else {
                return new Result<>(ResultEnum.SUCCESSFUL, userRespository.save(user));
            }
        }
    }

    @ApiOperation(value = "查询用户",notes = "用户信息")
    @GetMapping("/user")
    public Result Query(){
        return new Result(ResultEnum.SUCCESSFUL,userRespository.findAll());
    }

}
